package com.lou;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import com.lou.enity.User;

/**
 * @author : ljl
 * @date 创建时间：2018年9月11日 下午3:34:37
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
@Slf4j
public class TestReflect {
	public static void main(String[] args) {
		//自己随便写个实体类，写好对应的set,get方法
		User user = new User();
		System.out.println(getFiledsInfo(user));
	}

	private static List<Map<String, Object>> getFiledsInfo(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < fields.length; i++) {
			Map<String, Object> infoMap = new HashMap<String, Object>(3);
			infoMap.put("type", fields[i].getType().toString());
			infoMap.put("name", fields[i].getName());
			infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
			list.add(infoMap);
		}
		return list;
	}
	
	private static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}

}
